// DOM 元素
const addBtn = document.getElementById('addBtn');
const exportBtn = document.getElementById('exportBtn');
const clearAllBtn = document.getElementById('clearAllBtn');
const articleList = document.getElementById('articleList');
const articleCount = document.getElementById('articleCount');
const listCount = document.getElementById('listCount');
const emptyState = document.getElementById('emptyState');
const tip = document.getElementById('tip');
const filenameInput = document.getElementById('filenameInput');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  loadArticles();
  setupEventListeners();
  initFilename();
});

// 初始化文件名（从存储读取，否则使用默认值）
async function initFilename() {
  const { exportFilename } = await chrome.storage.local.get('exportFilename');
  if (exportFilename) {
    filenameInput.value = exportFilename;
  } else {
    const today = new Date().toISOString().split('T')[0];
    filenameInput.value = `微信文章_${today}`;
  }
}

// 设置事件监听
function setupEventListeners() {
  addBtn.addEventListener('click', handleAddArticle);
  exportBtn.addEventListener('click', handleExport);
  clearAllBtn.addEventListener('click', handleClearAll);
  
  // 文件名输入框失焦时保存
  filenameInput.addEventListener('blur', saveFilename);
  filenameInput.addEventListener('input', saveFilename);
}

// 保存文件名到存储
function saveFilename() {
  const filename = filenameInput.value.trim();
  if (filename) {
    chrome.storage.local.set({ exportFilename: filename });
  }
}

// 加载文章列表
async function loadArticles() {
  const { articles = [] } = await chrome.storage.local.get('articles');
  renderArticles(articles);
}

// 渲染文章列表
function renderArticles(articles) {
  // 更新计数
  articleCount.textContent = `${articles.length} 篇`;
  listCount.textContent = articles.length;
  
  // 更新导出按钮状态
  exportBtn.disabled = articles.length === 0;
  
  // 显示/隐藏空状态
  if (articles.length === 0) {
    emptyState.classList.remove('hidden');
    articleList.innerHTML = '';
    articleList.appendChild(emptyState);
    return;
  }
  
  emptyState.classList.add('hidden');
  
  // 渲染列表
  articleList.innerHTML = articles.map(article => `
    <div class="article-item" data-id="${article.id}">
      <div class="article-info" title="点击打开文章">
        <div class="article-title">${escapeHtml(article.title || '无标题')}</div>
        <div class="article-meta">
          <span>📝 ${escapeHtml(article.author || '未知公众号')}</span>
          <span>📅 ${formatDate(article.publishTime)}</span>
        </div>
      </div>
      <button class="delete-btn" title="删除">×</button>
    </div>
  `).join('');
  
  // 绑定点击事件
  articleList.querySelectorAll('.article-info').forEach(el => {
    el.addEventListener('click', () => {
      const id = el.parentElement.dataset.id;
      const article = articles.find(a => a.id === id);
      if (article) {
        chrome.tabs.create({ url: article.url });
      }
    });
  });
  
  // 绑定删除事件
  articleList.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = btn.parentElement.dataset.id;
      handleDelete(id);
    });
  });
}

// 添加当前文章
async function handleAddArticle() {
  // 获取当前标签页
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  
  if (!tab) {
    showTip('无法获取当前标签页', 'error');
    return;
  }
  
  // 检查是否是微信文章页面
  if (!tab.url || !tab.url.includes('mp.weixin.qq.com')) {
    showTip('请在微信公众号文章页面使用', 'error');
    return;
  }
  
  // 禁用按钮
  addBtn.disabled = true;
  addBtn.textContent = '添加中...';
  
  try {
    // 注入脚本提取数据
    const results = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      func: extractArticleData
    });
    
    if (results && results[0] && results[0].result) {
      const articleData = results[0].result;
      const saveResult = await saveArticle(articleData);
      
      showTip(saveResult.message, saveResult.type);
      
      // 刷新列表
      await loadArticles();
    } else {
      showTip('提取文章数据失败', 'error');
    }
  } catch (error) {
    console.error('添加文章失败:', error);
    showTip('添加失败：' + error.message, 'error');
  } finally {
    // 恢复按钮
    addBtn.disabled = false;
    addBtn.innerHTML = '<span class="btn-icon">+</span>添加当前文章';
  }
}

// 提取文章数据（注入到页面执行）
function extractArticleData() {
  // 提取标题
  const titleEl = document.querySelector('#activity-name');
  const titleMeta = document.querySelector('meta[property="og:title"]');
  const title = titleEl?.textContent?.trim() || titleMeta?.content?.trim() || '';
  
  // 提取公众号名称
  const authorEl = document.querySelector('#js_name');
  const authorMeta = document.querySelector('meta[property="og:article:author"]');
  const author = authorEl?.textContent?.trim() || authorMeta?.content?.trim() || '';
  
  // 提取发布时间
  const timeEl = document.querySelector('#publish_time');
  const timeMeta = document.querySelector('meta[property="article:published_time"]');
  const publishTime = timeEl?.textContent?.trim() || timeMeta?.content?.trim() || '';
  
  // 获取链接
  const url = window.location.href;
  
  return { title, author, publishTime, url };
}

// 保存文章
async function saveArticle(articleData) {
  const { articles = [] } = await chrome.storage.local.get('articles');
  
  // 检查重复
  const cleanUrl = (url) => {
    try {
      const urlObj = new URL(url);
      return urlObj.origin + urlObj.pathname;
    } catch {
      return url;
    }
  };
  
  const newUrlClean = cleanUrl(articleData.url);
  const isDuplicate = articles.some(article => cleanUrl(article.url) === newUrlClean);
  
  if (isDuplicate) {
    return { type: 'warning', message: '该文章已存在，请勿重复添加' };
  }
  
  // 生成ID并保存
  const id = Date.now().toString(36) + Math.random().toString(36).substr(2);
  const newArticle = {
    id,
    title: articleData.title,
    author: articleData.author,
    publishTime: articleData.publishTime,
    url: articleData.url,
    addedTime: new Date().toISOString()
  };
  
  articles.unshift(newArticle);
  await chrome.storage.local.set({ articles });
  
  return {
    type: 'success',
    message: `添加成功：${articleData.title.substring(0, 15)}${articleData.title.length > 15 ? '...' : ''}`
  };
}

// 删除单篇文章
async function handleDelete(id) {
  const { articles = [] } = await chrome.storage.local.get('articles');
  const newArticles = articles.filter(a => a.id !== id);
  await chrome.storage.local.set({ articles: newArticles });
  
  showTip('已删除', 'success');
  await loadArticles();
}

// 清空全部
async function handleClearAll() {
  const { articles = [] } = await chrome.storage.local.get('articles');
  
  if (articles.length === 0) {
    showTip('列表已经是空的', 'warning');
    return;
  }
  
  // 显示自定义确认对话框
  const confirmed = await showConfirm(
    '清空全部文章',
    `确定要清空全部 ${articles.length} 篇文章吗？此操作不可恢复。`
  );
  
  if (!confirmed) return;
  
  await chrome.storage.local.set({ articles: [] });
  showTip('已清空全部文章', 'success');
  await loadArticles();
}

// 显示自定义确认对话框
function showConfirm(title, message) {
  return new Promise((resolve) => {
    const overlay = document.getElementById('confirmOverlay');
    const titleEl = document.getElementById('confirmTitle');
    const messageEl = document.getElementById('confirmMessage');
    const cancelBtn = document.getElementById('confirmCancel');
    const okBtn = document.getElementById('confirmOk');
    
    titleEl.textContent = title;
    messageEl.textContent = message;
    overlay.style.display = 'flex';
    
    // 添加入场动画
    overlay.style.opacity = '0';
    requestAnimationFrame(() => {
      overlay.style.transition = 'opacity 0.2s ease';
      overlay.style.opacity = '1';
    });
    
    const cleanup = (result) => {
      overlay.style.opacity = '0';
      setTimeout(() => {
        overlay.style.display = 'none';
        resolve(result);
      }, 200);
    };
    
    // 点击取消
    const handleCancel = () => {
      cancelBtn.removeEventListener('click', handleCancel);
      okBtn.removeEventListener('click', handleOk);
      cleanup(false);
    };
    
    // 点击确定
    const handleOk = () => {
      cancelBtn.removeEventListener('click', handleCancel);
      okBtn.removeEventListener('click', handleOk);
      cleanup(true);
    };
    
    cancelBtn.addEventListener('click', handleCancel);
    okBtn.addEventListener('click', handleOk);
  });
}

// 导出CSV
async function handleExport() {
  const { articles = [] } = await chrome.storage.local.get('articles');
  
  if (articles.length === 0) {
    showTip('没有可导出的文章', 'warning');
    return;
  }
  
  // 构建CSV内容
  const header = 'title,link,create_time\n';
  const rows = articles.map(article => {
    return [
      escapeCsvField(article.title || ''),
      escapeCsvField(article.url || ''),
      escapeCsvField(article.publishTime || '')
    ].join(',');
  }).join('\n');
  
  const csvContent = '\ufeff' + header + rows; // BOM for Excel UTF-8
  
  // 获取用户输入的文件名
  const userFilename = filenameInput.value.trim() || `微信文章_${new Date().toISOString().split('T')[0]}`;
  const filename = `${userFilename}.csv`;
  
  // 创建下载
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  
  try {
    await chrome.downloads.download({
      url: url,
      filename: filename,
      saveAs: true
    });
    showTip(`导出成功：${articles.length} 篇文章`, 'success');
  } catch (error) {
    console.error('导出失败:', error);
    showTip('导出失败：' + error.message, 'error');
  }
}

// 显示提示
function showTip(message, type = 'success') {
  tip.textContent = message;
  tip.className = `tip show ${type}`;
  
  setTimeout(() => {
    tip.classList.remove('show');
  }, 3000);
}

// 工具函数：转义HTML
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// 工具函数：转义CSV字段
function escapeCsvField(field) {
  if (field.includes(',') || field.includes('"') || field.includes('\n')) {
    return `"${field.replace(/"/g, '""')}"`;
  }
  return `"${field}"`;
}

// 工具函数：格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '未知';
  // 如果已经是简单格式，直接返回
  if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
    return dateStr;
  }
  // 尝试解析
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    return date.toLocaleDateString('zh-CN');
  } catch {
    return dateStr;
  }
}

// 工具函数：格式化日期时间
function formatDateTime(isoStr) {
  if (!isoStr) return '';
  try {
    const date = new Date(isoStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return isoStr;
  }
}

